package com.example.fontone;

import ohos.agp.components.Text;
import ohos.agp.text.Font;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;

import java.io.*;

/**
 * @author pig
 */
public class FontOne {

    private static File file = null;

    private static File setTypeface(Context context, String name) throws IOException {

        File file = new File(context.getCodeCacheDir(), "text");
        OutputStream outputStream = null;
        ResourceManager resManager = context.getResourceManager();
        RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/" + name);

        Resource resource = null;
        try {
            resource = rawFileEntry.openRawFile();

            outputStream = new FileOutputStream(file);
            int index;
            byte[] bytes = new byte[1024];
            if (resource != null) {
                while ((index = resource.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, index);
                    outputStream.flush();
                }
            }
        } catch (FileNotFoundException | NullPointerException ignored) {
        } finally {
            resource.close();
            outputStream.close();
        }
        return file;
    }

    public static void setFont(Context context, Text text, String name){
        if (file == null){
            try {
                file = setTypeface(context, name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Font.Builder builder = new Font.Builder(file);
        Font font = builder.build();
        text.setFont(font);
    }
}
